package com.ruoyi.project.tool.backupSql.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class ExportSql {

	public Map<String, String> proRead(String proName) {
		Properties pro = new Properties();
		Map<String, String> mpro = new HashMap<String, String>();
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(getClass().getResourceAsStream(proName), "UTF-8");
			pro.load(isr);
			@SuppressWarnings("rawtypes")
			Enumeration en = pro.propertyNames();
			while (en.hasMoreElements()) {
				String key = (String) en.nextElement();
				String value = pro.getProperty(key);
				mpro.put(key, value);

			}
			return mpro;
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return null;

	}

	public void exportSql(String table, String users, String passwords, String exportDatabaseNames)
			throws InterruptedException {

		String user = users;
		String password = passwords;
		String exportDatabaseName = exportDatabaseNames;
		String exportPath = "c:\\mysql\\" + table + ".sql";
		String command = new String("cmd /c c:\\mysqldump -u" + user + " -p" + password + " " + exportDatabaseName + " "
				+ table + " " + " >" + exportPath);
		System.out.println(command);
		Runtime runtime = Runtime.getRuntime();
		try {
			Process process = runtime.exec(command);
			process.waitFor();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public HttpServletResponse downLoadFiles(List<File> files, HttpServletResponse response) throws Exception {

		try {
			// List<File> 作为参数传进来，就是把多个文件的路径放到一个list里面
			// 创建一个临时压缩文件

			// 临时文件可以放在CDEF盘中，但不建议这么做，因为需要先设置磁盘的访问权限，最好是放在服务器上，方法最后有删除临时文件的步骤

			String zipFilename = "C:/tempFile.zip";
			File file = new File(zipFilename);
			file.createNewFile();
			if (!file.exists()) {
				file.createNewFile();
			}
			response.reset();
			// response.getWriter()
			// 创建文件输出流
			FileOutputStream fous = new FileOutputStream(file);
			ZipOutputStream zipOut = new ZipOutputStream(fous);
			zipFile(files, zipOut);
			zipOut.close();
			fous.close();
			return downloadZip(file, response);
		} catch (Exception e) {
			System.out.println("发生getOutStream()错误，不影响系统运行");
		}
		return response;
	}

	public void zipFile(List files, ZipOutputStream outputStream) {
		int size = files.size();
		for (int i = 0; i < size; i++) {
			File file = (File) files.get(i);
			zipFile(file, outputStream);
		}
	}

	public void zipFile(File inputFile, ZipOutputStream ouputStream) {
		try {
			if (inputFile.exists()) {
				if (inputFile.isFile()) {
					FileInputStream IN = new FileInputStream(inputFile);
					BufferedInputStream bins = new BufferedInputStream(IN, 512);
					ZipEntry entry = new ZipEntry(inputFile.getName());
					ouputStream.putNextEntry(entry);
					// 向压缩文件中输出数据
					int nNumber;
					byte[] buffer = new byte[512];
					while ((nNumber = bins.read(buffer)) != -1) {
						ouputStream.write(buffer, 0, nNumber);
					}
					// 关闭创建的流对象
					bins.close();
					IN.close();
				} else {
					try {
						File[] files = inputFile.listFiles();
						for (int i = 0; i < files.length; i++) {
							zipFile(files[i], ouputStream);
						}
					} catch (Exception e) {
						System.out.println("发生getOutStream()错误，不影响系统运行");
					}
				}
			}
		} catch (Exception e) {
			System.out.println("发生getOutStream()错误，不影响系统运行");
		}
	}

	public HttpServletResponse downloadZip(File file, HttpServletResponse response) {
		if (file.exists() == false) {
			System.out.println("待压缩的文件目录：" + file + "不存在.");
		} else {
			try {
				// 以流的形式下载文件。
				InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
				byte[] buffer = new byte[fis.available()];
				fis.read(buffer);
				fis.close();
				// 清空response
				response.reset();
				ServletOutputStream outStream = response.getOutputStream();
				OutputStream toClient = new BufferedOutputStream(outStream);
				response.setContentType("application/octet-stream");

				// 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
				toClient.write(buffer);
				toClient.flush();
				toClient.close();
				outStream.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
				try {
					File f = new File(file.getPath());
					f.delete();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return response;
	}

}
